
const db = require('db');
const log = require('tools/log');
const evaluate = require('tools/evaluate');
const { addLogging } = require('tools/sqlString');

module.exports = async ctx => {
    const { connection, run } = db.init();

    await run('BEGIN'); // 开始事务

    try {
        await update(ctx, run);
        await createSettlementEntry(await queryOrder(ctx, run), run);
        await addLog(ctx, run);
        await run('COMMIT');
        ctx.body = 'ok';
        ctx.status = 200;
    } catch (error) {
        await run('ROLLBACK');
        ctx.status = error.status;
        ctx.body = error.err;

        log('---------------------------------------------------')
        console.log(error);
    }

    connection.end();
}

/** 修改订单数据 */
async function update(ctx, run) {
    const id = ctx.params.id;
    const body = ctx.request.body;
    const sql = toSqlString(id, { ...body, orderStatus: '制作完成', log: undefined });
    const result = await run(sql);
    if (result.err) {
        throw { err: result.err, status: 501 }
    }
}

/** 添加日志 */
async function addLog(ctx, run) {
    const id = ctx.params.id;
    const value = {
        source: 'order',
        group: `${id}`,
        value: `【制作完成】\n--------------------\n`+ctx.request.body.log,
        type: '用户',
    }
    await addLogging(value, ctx.header.authorization, run)
}

/** 查询订单数据 */
async function queryOrder(ctx, run) {
    const id = ctx.params.id;
    const sql = `SELECT * FROM orders WHERE id=${id}`
    const result = await run(sql);
    if (result.err) {
        throw { err: result.err, status: 502 }
    }
    if (!result.rows[0]) {
        throw { err: '订单不存在', status: 503 };
    }
    return result.rows[0];
}

/** 创建结算条目 */
async function createSettlementEntry(order, run) {
    const ordersId = order.id;
    const sql = `INSERT INTO settlementEntry (ordersId, unsettlementAmount) VALUES (${ordersId}, ${evaluate(`${order.businessDay}*${order.price}`)})`;
    const result = await run(sql)
    if (result.err) {
        throw { err: result.err, status: 504 };
    }
}

// -------------------------------------------------------------

/** 更新订单SLQ */
function toSqlString(id, body) {
    const keys = []
    for (key in body) {
        if (body[key])
            keys.push(`${key}=${typeof body[key] === 'string' ? `'${body[key]}'` : body[key]}`);
    }
    const sql = `
        UPDATE orders SET ${keys.join(',')}
        WHERE id = ${id}
    `;
    return sql;
}